
//=======================================================
//  
//=======================================================

module eg4_vga_text_demo(

	//////////// CLOCK //////////

	input 		          		CLK24M,				//24MHz clock input
	//input								clk_vga, //TESTING ONLY

	//////////// KEY //////////
	input 		     [1:0]		KEY,

	input                       WE,
	input                       ALE,

	//////////// SW //////////
	input 		     [15:0]		SW,
	output           [15:0]		LED,

	//////////// VGA //////////
	output		     [7:0]		VGA_B,
	output		     [7:0]		VGA_G,
	output		          		VGA_HS,
	output		     [7:0]		VGA_R,
	output                      VGA_CLK,
	output		          		VGA_VS
);

reg [11:0] address_latch;		//latch the address
reg [2:0]  wr_sync;
assign LED = ~address_latch;

wire clk,	clk_vga;
assign clk = CLK24M;

always@( posedge ALE )begin
	address_latch <= SW[11:0];
end

always@(posedge clk_vga)begin
	wr_sync[0] <= WE;
	wr_sync[1] <= wr_sync[0];
	wr_sync[2] <= wr_sync[1];
end

//VGA clock IP
vga_clk u0 (
		.refclk        		(clk),            	//      ref_clk.clk
		.reset    			(1'b0),    			//    ref_reset.reset
		.clk1_out        	(clk_vga)         	//      vga_clk.clk
);

textvga_top#(

    .INIT_FRAME_ENABLE             ("ENABLE"),                         //enable frame initial with CHAR and COLOR file
	.INIT_FRAME_CHAR_FILE_NAME     ("../rom/example_char.txt"),        //this file is for frame init, can be nothing
    .INIT_FRAME_COLOR_FILE_NAME    ("../rom/example_color.txt"),       //this file is for frame init, can be nothing
	.INIT_FRAME_BLINK_FILE_NAME	   ("../rom/example_blink.txt"),
    .INIT_CHAR_ROM_FILE_NAME       ("../rom/font.txt")                 //this rom is for char's shape, must have it!  

)vga_crtc(

    .sysclk_i			(clk),           		//system clock, can be any value, here we use 24MHz on board clock
    .vgaclk_i			(clk_vga),           	//must use 25MHz for vga clock, +-100MHz might be OK, depending on your monitor
    .rst_i				(~KEY[0]),              //async reset
    .pallete_select		(2'b00),     			//select a pallete to use, default=00 is IBM PC/XT's color shape!

    .charram_addr_i		(address_latch),     
	.colorram_addr_i	(address_latch),
    .charram_wren_i		(!wr_sync[2]),
	.colorram_wren_i	(!wr_sync[2]),
    .charram_data_i		(SW[7:0]),
	.colorram_data_i	(SW[15:8]),
    .charram_data_o		(),
	.colorram_data_o	(),

	.vga_b_o			(VGA_B),
	.vga_g_o			(VGA_G),
	.vga_hs_o			(VGA_HS),
	.vga_r_o			(VGA_R),
	.vga_vs_o			(VGA_VS)

);

assign VGA_CLK = clk_vga;

endmodule
